package com.adcc.loadsheet.billing.controller;

import com.adcc.loadsheet.billing.security.CookieUtil;
import com.adcc.loadsheet.billing.security.JWTFactory;
import com.adcc.loadsheet.billing.util.MD5Util;
import com.adcc.loadsheet.billing.util.validatecode.ValidateCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: zhaoml
 * @Date: 2020/4/10
 * @Description: 跳转登录页
 */
@Controller
public class LoginController {

    /**
     * 进入登录页面
     *
     * @return
     */
    @GetMapping(value = {"/", "/login"})
    @ApiOperation(value = "/login", notes = "跳转到登录页", httpMethod = "GET")
    public String toLogin(HttpServletRequest request) {
        return "login";
    }

    @ApiOperation(value = "生成验证码")
    @GetMapping("/verifycode")
    @ResponseBody
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        try {
//            HttpSession session = request.getSession();

            // 设置响应的类型格式为图片格式
            response.setContentType("image/jpeg");
            //禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            ValidateCode vCode = new ValidateCode(120,40,4,100);
            response.addCookie(CookieUtil.setCookie("validateCode", MD5Util.StringMD5(vCode.getCode()),-1,"",true));
//            session.setAttribute("validateCode", vCode.getCode());
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping(value = {"/logout"})
    @ApiOperation(value = "/logout", notes = "登出跳转到登录页", httpMethod = "GET")
    public String logout(HttpServletRequest request,HttpServletResponse response) {
        response.addCookie(CookieUtil.setCookie("loadsheetbilltoken",null,-1,"",true));
        return "login";
    }
}